// 简单的象棋AI实现
import DataBus from '../databus'

export default class GameAI {
  constructor() {
    this.databus = new DataBus()
    this.rows = 10 // 10行
    this.cols = 9 // 9列
    this.difficulty = 'medium'
  }

  /**
   * 设置AI难度
   */
  setDifficulty(difficulty) {
    this.difficulty = difficulty
  }

  /**
   * 获取AI的下一步移动
   */
  getNextMove(board, player) {
    const depth = this.getSearchDepth()
    const result = this.search(board, depth, player)
    
    if (result && result.move) {
      return result.move
    }
    
    // 如果没有找到最佳走法，返回一个随机移动
    return this.getRandomMove(board, player)
  }

  /**
   * 根据难度获取搜索深度
   */
  getSearchDepth() {
    switch (this.difficulty) {
      case 'easy': return 2
      case 'medium': return 3
      case 'hard': return 4
      default: return 3
    }
  }

  /**
   * 获取所有可能的移动
   */
  getAllMoves(board, player) {
    const moves = []
    
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.cols; j++) {
        const piece = board[i][j]
        if (piece && piece.player === player) {
          // 获取该棋子的所有可能移动
          const pieceMoves = this.getPieceMoves(board, i, j, piece, player)
          moves.push(...pieceMoves)
        }
      }
    }
    
    return moves
  }

  /**
   * 获取指定棋子的所有可能移动
   */
  getPieceMoves(board, row, col, piece, player) {
    const moves = []
    
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.cols; j++) {
        if (this.databus.isValidMove(row, col, i, j, player)) {
          moves.push({
            fromRow: row,
            fromCol: col,
            toRow: i,
            toCol: j,
            piece: piece
          })
        }
      }
    }
    
    return moves
  }

  /**
   * 评估棋盘状态
   */
  evaluate(board, player) {
    let score = 0
    
    // 棋子价值表
    const pieceValues = {
      'jiang': 10000, // 将/帅
      'shi': 20,      // 士/仕
      'xiang': 20,    // 象/相
      'ma': 40,       // 马
      'che': 90,      // 车
      'pao': 45,      // 炮
      'bing': 10      // 兵/卒
    }
    
    // 位置价值表（简化版）
    const positionValues = {
      'jiang': [
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0]
      ]
    }
    
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.cols; j++) {
        const piece = board[i][j]
        if (piece) {
          const value = pieceValues[piece.type] || 0
          const positionValue = positionValues[piece.type] ? positionValues[piece.type][i][j] : 0
          const totalValue = value + positionValue
          
          if (piece.player === player) {
            score += totalValue
          } else {
            score -= totalValue
          }
        }
      }
    }
    
    return score
  }

  /**
   * 搜索最佳移动
   */
  search(board, depth, player) {
    const moves = this.getAllMoves(board, player)
    let bestMove = null
    let bestScore = player === 1 ? -Infinity : Infinity
    
    for (const move of moves) {
      // 执行移动
      const capturedPiece = board[move.toRow][move.toCol]
      board[move.toRow][move.toCol] = move.piece
      board[move.fromRow][move.fromCol] = 0
      
      // 递归搜索
      const score = this.minimax(board, depth - 1, -Infinity, Infinity, player === 2, player === 1 ? 2 : 1)
      
      // 撤销移动
      board[move.fromRow][move.fromCol] = move.piece
      board[move.toRow][move.toCol] = capturedPiece
      
      // 更新最佳移动
      if (player === 1) {
        if (score > bestScore) {
          bestScore = score
          bestMove = move
        }
      } else {
        if (score < bestScore) {
          bestScore = score
          bestMove = move
        }
      }
    }
    
    return { move: bestMove, score: bestScore }
  }

  /**
   * Minimax算法
   */
  minimax(board, depth, alpha, beta, isMaximizing, player) {
    if (depth === 0) {
      return this.evaluate(board, player)
    }
    
    const moves = this.getAllMoves(board, player)
    
    if (isMaximizing) {
      let maxScore = -Infinity
      for (const move of moves) {
        const capturedPiece = board[move.toRow][move.toCol]
        board[move.toRow][move.toCol] = move.piece
        board[move.fromRow][move.fromCol] = 0
        
        const score = this.minimax(board, depth - 1, alpha, beta, false, player === 1 ? 2 : 1)
        
        board[move.fromRow][move.fromCol] = move.piece
        board[move.toRow][move.toCol] = capturedPiece
        
        maxScore = Math.max(maxScore, score)
        alpha = Math.max(alpha, score)
        if (beta <= alpha) break
      }
      return maxScore
    } else {
      let minScore = Infinity
      for (const move of moves) {
        const capturedPiece = board[move.toRow][move.toCol]
        board[move.toRow][move.toCol] = move.piece
        board[move.fromRow][move.fromCol] = 0
        
        const score = this.minimax(board, depth - 1, alpha, beta, true, player === 1 ? 2 : 1)
        
        board[move.fromRow][move.fromCol] = move.piece
        board[move.toRow][move.toCol] = capturedPiece
        
        minScore = Math.min(minScore, score)
        beta = Math.min(beta, score)
        if (beta <= alpha) break
      }
      return minScore
    }
  }

  /**
   * 获取随机移动
   */
  getRandomMove(board, player) {
    const moves = this.getAllMoves(board, player)
    if (moves.length === 0) return null
    
    const randomIndex = Math.floor(Math.random() * moves.length)
    return moves[randomIndex]
  }

  /**
   * 获取AI信息
   */
  getAIInfo() {
    return {
      difficulty: this.difficulty,
      searchDepth: this.getSearchDepth(),
      type: '象棋AI'
    }
  }

  /**
   * 获取性能报告
   */
  getPerformanceReport() {
    return {
      difficulty: this.difficulty,
      searchDepth: this.getSearchDepth(),
      type: '象棋AI'
    }
  }

  /**
   * 获取性能监控器
   */
  getPerformanceMonitor() {
    return {
      getStats: () => ({
        difficulty: this.difficulty,
        searchDepth: this.getSearchDepth()
      })
    }
  }

  /**
   * 清除缓存
   */
  clearCache() {
    // 象棋AI暂时不需要缓存
  }

  /**
   * 检查是否超时
   */
  isTimeUp() {
    return false
  }
} 